<template>
  <div class="tourist-info">
    <h3>游客信息</h3>

    <!-- 联系人信息 -->
    <div class="info-card">
      <h4>联系人信息</h4>
      <div class="form-grid">
        <div class="form-group">
          <label>姓名 *</label>
          <input
            v-model="contactInfo.name"
            type="text"
            placeholder="请输入联系人姓名"
            @input="updateTouristInfo"
          />
        </div>
        <div class="form-group">
          <label>身份证号 *</label>
          <input
            v-model="contactInfo.idCard"
            type="text"
            placeholder="请输入身份证号"
            @input="updateTouristInfo"
          />
        </div>
        <div class="form-group">
          <label>手机号 *</label>
          <input
            v-model="contactInfo.phone"
            type="tel"
            placeholder="请输入手机号"
            @input="updateTouristInfo"
          />
        </div>
      </div>
    </div>

    <!-- 代预约游客信息 -->
    <div v-if="ticketCount > 1" class="info-card">
      <h4>代预约游客信息</h4>
      <div v-for="(guest, index) in guestList" :key="index" class="guest-info">
        <h5>游客{{ index + 1 }}</h5>
        <div class="form-grid">
          <div class="form-group">
            <label>姓名 *</label>
            <input
              v-model="guest.name"
              type="text"
              :placeholder="`请输入游客${index + 1}姓名`"
              @input="updateTouristInfo"
            />
          </div>
          <div class="form-group">
            <label>身份证号 *</label>
            <input
              v-model="guest.idCard"
              type="text"
              :placeholder="`请输入游客${index + 1}身份证号`"
              @input="updateTouristInfo"
            />
          </div>
          <div class="form-group">
            <label>手机号 *</label>
            <input
              v-model="guest.phone"
              type="tel"
              :placeholder="`请输入游客${index + 1}手机号`"
              @input="updateTouristInfo"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 支付按钮 -->
    <div v-if="showPayment" class="payment-section">
      <div class="total-info">
        <div class="total-row">
          <span class="total-tickets">共{{ ticketCount }}张门票</span>
          <span class="total-price">总计：¥{{ totalPrice }}</span>
        </div>
      </div>
      <button
        class="payment-btn"
        :disabled="!isPaymentButtonEnabled"
        @click="proceedToPayment"
      >
        去支付
      </button>
    </div>

    <!-- 未选择日期时的提示 -->
    <div v-else class="date-reminder">
      <p>请先选择预约日期后再进行支付</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { createOrderWithPayment } from "@/api/orders";
import { getCurrentUserId } from "@/stores/user";

const props = defineProps({
  ticketCount: {
    type: Number,
    required: true,
  },
  selectedDate: {
    type: Date,
    default: null,
  },
  spot: {
    type: Object,
    default: () => ({}),
  },
  showPayment: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["tourist-info-updated", "proceed-to-payment"]);
const router = useRouter();

const contactInfo = ref({
  name: "",
  idCard: "",
  phone: "",
});

const guestList = ref([]);

// 计算总价
const totalPrice = computed(() => {
  const basePrice = props.spot?.basePrice || 190;
  return props.ticketCount * basePrice;
});

// 监听门票数量变化，动态调整游客列表
watch(
  () => props.ticketCount,
  (newCount) => {
    const guestCount = newCount - 1; // 减去联系人

    if (guestCount > guestList.value.length) {
      // 增加游客
      for (let i = guestList.value.length; i < guestCount; i++) {
        guestList.value.push({
          name: "",
          idCard: "",
          phone: "",
        });
      }
    } else if (guestCount < guestList.value.length) {
      // 减少游客
      guestList.value.splice(guestCount);
    }
  },
  { immediate: true }
);

// 支付按钮启用条件 - 用户输入了联系人信息后就可以被点击
const isPaymentButtonEnabled = computed(() => {
  return (
    props.selectedDate !== null &&
    props.selectedDate !== undefined &&
    contactInfo.value.name &&
    contactInfo.value.idCard &&
    contactInfo.value.phone
  );
});

// 表单验证 - 完整的表单验证逻辑
const isFormValid = computed(() => {
  // 验证联系人信息
  const contactValid =
    contactInfo.value.name &&
    contactInfo.value.idCard &&
    contactInfo.value.phone &&
    isValidIdCard(contactInfo.value.idCard) &&
    isValidPhone(contactInfo.value.phone);

  if (!contactValid) return false;

  // 验证游客信息
  for (const guest of guestList.value) {
    if (
      !guest.name ||
      !guest.idCard ||
      !guest.phone ||
      !isValidIdCard(guest.idCard) ||
      !isValidPhone(guest.phone)
    ) {
      return false;
    }
  }

  return true;
});

// 身份证号验证
const isValidIdCard = (idCard) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(idCard);
};

// 手机号验证
const isValidPhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(phone);
};

// 更新游客信息
const updateTouristInfo = () => {
  emit("tourist-info-updated", {
    contact: contactInfo.value,
    guests: guestList.value,
  });
};

// 前往支付
const proceedToPayment = async () => {
  // 首先检查日期是否已选择
  if (!props.selectedDate) {
    alert("请先选择预约日期");
    return;
  }

  // 然后进行完整的表单验证
  if (!isFormValid.value) {
    // 检查联系人信息
    if (!contactInfo.value.name) {
      alert("请输入联系人姓名");
      return;
    }
    if (!contactInfo.value.idCard || !isValidIdCard(contactInfo.value.idCard)) {
      alert("请输入有效的身份证号");
      return;
    }
    if (!contactInfo.value.phone || !isValidPhone(contactInfo.value.phone)) {
      alert("请输入有效的手机号");
      return;
    }

    // 检查游客信息
    for (let i = 0; i < guestList.value.length; i++) {
      const guest = guestList.value[i];
      if (!guest.name) {
        alert(`请输入游客${i + 1}姓名`);
        return;
      }
      if (!guest.idCard || !isValidIdCard(guest.idCard)) {
        alert(`请输入游客${i + 1}有效的身份证号`);
        return;
      }
      if (!guest.phone || !isValidPhone(guest.phone)) {
        alert(`请输入游客${i + 1}有效的手机号`);
        return;
      }
    }

    return;
  }

  try {
    // 获取门票单价
    const ticketPrice = props.spot.basePrice || 190;

    // 准备订单数据，按照后端要求的格式
    const orderData = {
      orderInfo: {
        userId: getCurrentUserId() || 0, // 从用户状态中获取实际的用户ID
        scenicId: props.spot.id || 0, // 景点ID
        visitDate: props.selectedDate
          ? props.selectedDate.toISOString().split("T")[0]
          : "",
        totalAmount: totalPrice.value, // 总价 = 门票单价 * 游客数量
        orderStatus: 0,
      },
      touristList: [],
    };

    // 添加联系人信息到游客列表（isPrimary=1）
    orderData.touristList.push({
      realName: contactInfo.value.name,
      phone: contactInfo.value.phone,
      idCard: contactInfo.value.idCard,
      isPrimary: 1,
      ticketPrice: ticketPrice,
    });

    // 添加代预约游客信息到游客列表（isPrimary=0）
    for (const guest of guestList.value) {
      orderData.touristList.push({
        realName: guest.name,
        phone: guest.phone,
        idCard: guest.idCard,
        isPrimary: 0,
        ticketPrice: ticketPrice,
      });
    }

    // 调用后端API创建订单并准备支付
    const result = await createOrderWithPayment(orderData);

    // 打印调试信息
    console.log("API调用结果:", result);
    console.log("result.success:", result.success);
    console.log("result.code:", result.code);
    console.log("result.data:", result.data);

    // 如果API调用成功，跳转到支付页面
    if (result.success || result.code === 200) {
      console.log("满足跳转条件，准备跳转到支付页面");

      // 准备传递给支付页面的数据
      const ticketPrice = props.spot.basePrice || 190;
      const formattedOrderData = {
        // 重要：包含后端返回的订单ID
        id: result.data || 0, // 使用后端返回的订单ID
        
        // 景点信息
        scenicSpotName: props.spot.name || "未知景点",
        openingHours: props.spot.openingHours || "未知开放时间",
        contactPhone: props.spot.contactPhone || "未知联系电话",

        // 预约详情
        visitDate: props.selectedDate
          ? props.selectedDate.toISOString().split("T")[0]
          : "",
        createTime: new Date().toLocaleString("zh-CN"),
        unitPrice: ticketPrice,
        visitorCount: orderData.touristList.length,
        totalAmount: orderData.touristList.length * ticketPrice,

        // 游客信息
        mainVisitor: {
          name: contactInfo.value.name,
          idCard: contactInfo.value.idCard,
          phone: contactInfo.value.phone,
        },
        otherVisitors: guestList.value.map((guest) => ({
          name: guest.name,
          idCard: guest.idCard,
          phone: guest.phone,
        })),
      };

      console.log("格式化后的订单数据:", formattedOrderData);

      // 跳转到支付页面，传递格式化后的订单数据
      router.push({
        path: "/pay",
        query: {
          order: encodeURIComponent(JSON.stringify(formattedOrderData)),
        },
      });
    } else {
      console.log(
        "不满足跳转条件，success:",
        result.success,
        "code:",
        result.code
      );
    }
  } catch (error) {
    console.error("创建订单失败:", error);
    alert("创建订单失败，请重试");
  }
};
</script>

<style scoped>
.tourist-info {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
}

.tourist-info h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 25px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
}

.info-card h4 {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--secondary-color);
}

.guest-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.guest-info h5 {
  font-size: 16px;
  color: #555;
  margin-bottom: 15px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-size: 14px;
  color: #555;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: var(--secondary-color);
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.form-group input:invalid {
  border-color: #f44336;
}

.payment-section {
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.total-info {
  margin-bottom: 15px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.total-tickets {
  font-size: 14px;
  color: #666;
}

.total-price {
  font-size: 20px;
  font-weight: bold;
  color: var(--primary-color);
}

.payment-btn {
  background: var(--secondary-color);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 100%;
}

.payment-btn:hover:not(:disabled) {
  background: var(--secondary-color);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.payment-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.date-reminder {
  margin-top: 25px;
  padding: 20px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 6px;
  text-align: center;
}

.date-reminder p {
  margin: 0;
  color: #856404;
  font-size: 14px;
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .total-row {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
}
</style>
